package com.buddies.lottery.ui.home;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseBusEventFragment;
import com.buddies.lottery.data.bean.Banner;
import com.buddies.lottery.data.bean.Lottery;
import com.buddies.lottery.data.resp.HomeResponse;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.ui.help.HelpActivity;
import com.buddies.lottery.ui.lottery.detail.LotteryDetailActivity;
import com.buddies.lottery.utils.RedirectUtils;
import com.buddies.lottery.widget.OnTabClickListener;
import com.buddies.lottery.widget.SpaceItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseBusEventFragment<HomeContract.Presenter> implements HomeContract.View, OnTabClickListener {

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private com.youth.banner.Banner mBannerView;
    private List<Banner> mBanners = new ArrayList<>();

    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private HomeAdapter mAdapter;
    private List<Lottery> mItems = new ArrayList<>();
    private TextView tvMessage;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView() {
        ((TextView) findViewById(R.id.tv_title)).setText(R.string.app_name);
        ((ImageView) findViewById(R.id.iv_up)).setImageResource(R.mipmap.ic_launcher_round);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresher);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        tvMessage = (TextView) findViewById(R.id.tv_message);
        tvMessage.setSelected(true);
        tvMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HelpActivity.launch(getActivity(), "公告", tvMessage.getText().toString());
            }
        });

        mRecyclerView = findViewById(R.id.recycler_view);

        initBanner();
    }

    private void initBanner() {
        mBannerView = findViewById(R.id.banner);
        //设置banner样式
        mBannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBannerView.setImageLoader(new FrescoImageLoader());
        //设置banner动画效果
        mBannerView.setBannerAnimation(Transformer.Stack);
//        //设置标题集合（当banner样式有显示title时）
//        mBannerView.setBannerTitles(titles);
        //设置自动轮播，默认为true
        mBannerView.isAutoPlay(true);
        //设置轮播时间
        mBannerView.setDelayTime(1500);
        //设置指示器位置（当banner模式中有指示器时）
        mBannerView.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        mBannerView.start();
        mBannerView.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Banner banner = mBanners.get(position);
                RedirectUtils.redirect(banner.redirect_type, banner.redirect_id);
            }
        });
    }

    @Override
    public void initData() {
        mPresenter = new HomePresenter(this);

        mLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);

        mAdapter = new HomeAdapter(mItems);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener(){
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LotteryDetailActivity.launch(getActivity(), mItems.get(position));
            }
        });

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(ConvertUtils.dp2px(7)));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void forceRefresh() {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                mPresenter.loadHome();
            }
        });
    }

    @Override
    public void onLotteryListLoaded(HomeResponse response) {
        mSwipeRefreshLayout.setRefreshing(false);
        mBanners.clear();
        if (response.banners != null && !response.banners.isEmpty()) {
            mBanners.addAll(response.banners);
            mBannerView.update(response.banners);
        }

        if (response.messages != null && !response.messages.isEmpty()) {
            tvMessage.setText(response.messages.get(0).content);
        }

        if (!mItems.isEmpty()) {
            mItems.clear();
        }
        if (response.lotteries != null && !response.lotteries.isEmpty()) {
            mItems.addAll(response.lotteries);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        forceRefreshIfNeed();
    }

    @Override
    public void onPause() {
        super.onPause();
        mBannerView.stopAutoPlay();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        forceRefreshIfNeed();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        forceRefreshIfNeed();
    }

    private boolean isUserVisible() {
        return getUserVisibleHint() && getActivity() != null && ((MainActivity) getActivity()).getCurrentTab() == 0;
    }

    private void forceRefreshIfNeed() {
        if (isUserVisible()) {
            if (mBannerView != null) {
                mBannerView.startAutoPlay();
            }
            forceRefresh();
        } else {
            if (mBannerView != null) {
                mBannerView.stopAutoPlay();
            }
        }
    }

    @Override
    public void onTabClick() {
        if ((mLayoutManager != null && mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) || mItems.isEmpty()) {// 第一页
            forceRefresh();
        } else if (mRecyclerView != null && mLayoutManager != null) {
            int currentPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition();
            if (currentPosition > 12) {
                mRecyclerView.scrollToPosition(12);
            }
            mRecyclerView.smoothScrollToPosition(0);
        }
    }

}
